package com.xmu.prcs.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.xmu.prcs.action.bean.UserInfoBean;
import com.xmu.prcs.dao.RoleDao;
import com.xmu.prcs.dao.UserDao;
import com.xmu.prcs.dao.UserRoleDao;
import com.xmu.prcs.entity.Role;
import com.xmu.prcs.entity.User;
import com.xmu.prcs.entity.UserRole;
import com.xmu.prcs.service.UserManager;
import com.xmu.prcs.util.DictionaryUtil;
import com.xmu.prcs.util.EncryptHelper;
import com.xmu.prcs.util.PageBean;
import com.xmu.prcs.util.ResultBean;

public class UserManagerImpl implements UserManager {
	
	private UserDao userDao;
	
	private RoleDao roleDao;
	
	private UserRoleDao userRoleDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public UserRoleDao getUserRoleDao() {
		return userRoleDao;
	}

	public void setUserRoleDao(UserRoleDao userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	public boolean addUser(UserInfoBean user){
		//得到实体user对象
		User newUser = this.userBean2Entity(user);
		//初始化用户数据
		newUser.setStatus(DictionaryUtil.USER_STATUS_NORMAL);//用户状态
		newUser.setRegisterTime(new Date());
		newUser.setEgg(0);
		newUser.setFlower(0);
		//加密密码
		EncryptHelper encrypt = EncryptHelper.getInstance();
		
		newUser.setPassword(encrypt.encryptString(user.getPassword()));
		System.out.println("password:" + newUser.getPassword());
		//初始化用户角色，为普通用户角色
		Role role = roleDao.getRoleByLevel(DictionaryUtil.ROLE_LEVEL_COMMON).get(0);
		UserRole userRole = new UserRole();
		userRole.setRole(role);
		
		userRoleDao.save(userRole);
		
		Set<UserRole> userRoles = new HashSet<UserRole>();
		userRoles.add(userRole);
		newUser.setUserRole(userRoles);
		
		userDao.save(newUser);
		
		return true;
	}
	
	/**
	 * 将userInfoBean转换为实体User对象
	 */
	public User userBean2Entity(UserInfoBean user){
		
		User newUser = new User();
		
		newUser.setUserName(user.getName());
		newUser.setAddress(user.getAddress());
		newUser.setBirthday(user.getBirthday());
		newUser.setEmail(user.getEmail());
		newUser.setPhoto(user.getPhoto());
		if(user.getQqNumber() != null && !user.getQqNumber().equals("")){
			newUser.setQqNumber(Integer.parseInt(user.getQqNumber()));
		}
		if(user.getSex() != null && !user.getSex().equals("")){
			newUser.setSex(Integer.parseInt(user.getSex()));
		}
		newUser.setSignature(user.getSignature());
		if(user.getZip() != null && !user.getZip().equals("")){
			newUser.setZip(Integer.parseInt(user.getZip()));
		}
		
		return newUser;
	}

	public boolean isUserNameExist(String name) {
		List<User> list = userDao.findByProperty(UserDao.USER_NAME, name);
		if(list == null || list.size() == 0){
			return false;
		}
		return true;
	}

	public boolean isEmailExist(String email) {
		List<User> list = userDao.findByProperty(UserDao.EMAIL, email);
		if(list == null || list.size() == 0){
			return false;
		}
		return true;
	}

	public int getUserIdByUserName(String name) {
		List<User> users = userDao.findByProperty(UserDao.USER_NAME, name);
		if(users == null || users.size() == 0){
			return 0;
		}
		User user = users.get(0);
		if(user != null){
			return user.getIdUser().intValue();
		}
		return 0;
	}

	public UserInfoBean getUserById(String idUser){
		UserInfoBean userBean = null;
		if(idUser != null && !idUser.equals("")){
			User user = userDao.get(Integer.parseInt(idUser));
			userBean = this.userEntity2Bean(user);
		}
		return userBean;
	}
	
	public UserInfoBean userEntity2Bean(User user){
		UserInfoBean bean = null;
		if(user != null){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
			bean = new UserInfoBean();
			bean.setUserId(user.getIdUser());
			bean.setAddress(user.getAddress());
			bean.setBirthday(user.getBirthday());
			bean.setStatus(user.getStatus());
			System.out.println("date:" + user.getBirthday());
			bean.setDate(format.format(user.getBirthday()));
			bean.setEmail(user.getEmail());
			bean.setName(user.getUserName());
			if(user.getPhoto().equals(DictionaryUtil.DEFAULT_PHOTO)){
				bean.setPhoto(DictionaryUtil.DEFAULT_PHOTO_PATH);
			}else{
				bean.setPhoto(user.getPhoto());
			}
			if(user.getQqNumber() == null){
				bean.setQqNumber("");
			}else{
				bean.setQqNumber(user.getQqNumber().toString());
			}
			if(user.getSex() == DictionaryUtil.SEX_FEMALE){
				bean.setSex("女");
			}else if(user.getSex() == DictionaryUtil.SEX_MALE){
				bean.setSex("男");
			}else{
				bean.setSex("保密");
			}
			bean.setUsex(user.getSex());
			bean.setSignature(user.getSignature());
			if(user.getZip() == null){
				bean.setZip("");
			}else{
				bean.setZip(user.getZip().toString());
			}
		}
		return bean;
	}
	
	public boolean modifyUserInfo(int userId, UserInfoBean bean){
		User user = userDao.get(userId);
		user.setUserName(bean.getName());
		user.setAddress(bean.getAddress());
		user.setBirthday(bean.getBirthday());
		user.setEmail(bean.getEmail());
		if(!bean.getPhoto().equals(DictionaryUtil.DEFAULT_PHOTO)){
			user.setPhoto(bean.getPhoto());
		}
		if(bean.getQqNumber() != null && bean.getQqNumber().equals("")){
			user.setQqNumber(Integer.parseInt(bean.getQqNumber()));
		}
		if(bean.getSex() != null && bean.getSex().equals("")){
			user.setSex(Integer.parseInt(bean.getSex()));
		}
		user.setSignature(bean.getSignature());
		if(bean.getZip() != null && bean.getZip().equals("")){
			user.setZip(Integer.parseInt(bean.getZip()));
		}
		userDao.update(user);
		return true;
	}
	
	public ResultBean listUsers4page(PageBean page, String name){
		int count = userDao.countUsers(name);
		PageBean pagebean = new PageBean(count);
		pagebean.setCurrentPage(page.getCurrentPage());
		
		List<User> userList = userDao.find4page(page.getBeginIndex(), page.getPageSize(), name);
		List<UserInfoBean> beanList = new ArrayList<UserInfoBean>();
		if(userList != null && userList.size() != 0){
			UserInfoBean bean = new UserInfoBean();
			for(User user : userList){
				bean = this.userEntity2Bean(user);
				beanList.add(bean);
			}
		}
		
		ResultBean result = new ResultBean();
		result.setPage(pagebean);
		result.setContent(beanList);
		return result;
	}

	public boolean freezeUser(int userId) {
		if(userId == 0)
			return false;
		User user = userDao.get(userId);
		user.setStatus(DictionaryUtil.USER_STATUS_FREEZE);
		userDao.update(user);
		return true;
	}

	public boolean unfreezeUser(int userId) {
		if(userId == 0)
			return false;
		User user = userDao.get(userId);
		user.setStatus(DictionaryUtil.USER_STATUS_NORMAL);
		userDao.update(user);
		return true;
	}
	
	public int getUserRoleById(int userId){
		if(userId == 0){
			return 0;
		}
		int roleLevel = 0;
		User user = userDao.get(userId);
		Set<UserRole> userRoles = user.getUserRole();
		if(userRoles != null && userRoles.size() != 0){
			for(UserRole ur : userRoles){
				Role role = ur.getRole();
				if(role.getLevel() > roleLevel){//取级别最高的角色
					roleLevel = role.getLevel();
				}
			}
		}
		
		return roleLevel;
	}
	
	public List<UserInfoBean> getAllUsers(){
		List<UserInfoBean> users = new ArrayList<UserInfoBean>();
		List<User> userList = userDao.getAll();
		if(userList != null && userList.size() != 0){
			UserInfoBean bean;
			for(User user : userList){
				bean = new UserInfoBean();
				bean = this.userEntity2Bean(user);
				users.add(bean);
			}
		}
		return users;
	}

	public boolean addEgg4User(int userId) {
		User user = userDao.get(userId);
		user.setEgg(user.getEgg() + 1);
		userDao.update(user);
		return true;
	}

	public boolean addFlower4User(int userId) {
		User user = userDao.get(userId);
		user.setFlower(user.getFlower() + 1);
		userDao.update(user);
		return true;
	}
}
